//
//  CommentsViewController.m
//  Edumap
//
//  Created by 辰领科技 on 16/7/19.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "CommentsViewController.h"
#import "CommentsTableViewCell.h"

static NSString *CellIdentifier = @"CommentsTableViewCell";

@interface CommentsViewController ()
<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) IBOutlet UIButton *leftButton;
@property (strong, nonatomic) IBOutlet UIButton *centreButton;
@property (strong, nonatomic) IBOutlet UIButton *rightButton;
@property (strong, nonatomic) NSMutableArray *Array;

@end

@implementation CommentsViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _Array = [NSMutableArray array];
    _pageNO = 1;
    [self initViewLayout];
    [self addRefreshing];}

- (void)initViewLayout {
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellReuseIdentifier:CellIdentifier];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self MyComments];
        });
    }];
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.Array.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self MyComments];
        });
    }
    
}

#pragma mark - 切换评论类型列表
- (IBAction)comments:(UIButton *)sender {
    sender.selected = YES;
    if (sender == _leftButton) {            //全部
        _centreButton.selected = NO;
        _rightButton.selected = NO;
        
    } else if (sender == _centreButton) {   //家教
        _leftButton.selected = NO;
        _rightButton.selected = NO;


    } else if (sender == _rightButton) {    //培训
        _leftButton.selected = NO;
        _centreButton.selected = NO;

    }
    [_tableView.header beginRefreshing];
}


#pragma mark - 获取评论数据
- (void)MyComments {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"memberId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];
    self.shareApi.delegate=self;
    if (_leftButton.selected) {
        [self.shareApi  requestOperationWithDic:dic withPath:JY_commentList withHttpType:@"POST" withTag:JY_JY_commentList];
    } else if (_centreButton.selected) {
        [self.shareApi  requestOperationWithDic:dic withPath:mallLecturerComment withHttpType:@"POST" withTag:JY_JY_mallLecturerComment];
    }  else if (_rightButton.selected) {
        [self.shareApi  requestOperationWithDic:dic withPath:JY_mallGoodsCommentList withHttpType:@"POST" withTag:JY_JY_mallGoodsCommentList];
    }
    
}

#pragma mark - <UITableViewDelegate&&UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _Array.count;
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90*VerticalRatio();
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommentsTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell= [[CommentsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }

    NSString *imageStr = [NSString stringWithFormat:@"%@",self.Array[indexPath.row][@"image"]];
    if (imageStr && imageStr.length>0 && ![self.Array[indexPath.row][@"mgooImage"] isEqual:[NSNull null]]) {
        [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,imageStr]]];
    }
    cell.titleLabe.text = [NSString stringWithFormat:@"%@",self.Array[indexPath.row][@"name"]];
    cell.detailLabel.text = [NSString stringWithFormat:@"%@",self.Array[indexPath.row][@"comment"]];
    
    return cell;
}

//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - 返回
- (IBAction)Back:(id)sender {
    [self backBtn];
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==JY_JY_commentList || tag==JY_JY_mallLecturerComment || tag==JY_JY_mallGoodsCommentList) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.Array removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.Array addObject:entity];
                }
                self.tableView.delegate = self;
                self.tableView.dataSource = self;
                [_tableView reloadData];                
            });

        }

    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    [self dismissWaitDialog];
    
    
}



@end
